import 'css-modules-require-hook/preset';

import path from 'path';
import Koa from 'koa';
import mount from 'koa-mount';
import gzip from 'koa-compress';
import serve from 'koa-static';
import favicon from 'koa-favicon';
import util from 'util';
import koajwt from 'koa-jwt';
import koabody from 'koa-body';
import * as config from '../src/config';

// init pre-router and middleware
import serverRender from './tools/serverRender';
import middleware from './middleware/middleware';

const isDev = process.env.NODE_ENV;

const app = new Koa();
const secret = 'swust';

// 接口错误日志打印
app.on('error', (err, errId) => {
    global.logger.error('[app error]: %j - %s - %s ', util.inspect(err), errId, err.stack);
});

app.use(koabody());

app.use(koajwt({secret}).unless({
    path: [/^\//] // 数组中的路径不需要通过jwt验证
}));
app.proxy = true;
app.use(gzip());
// app.use(favicon(path.join(__dirname, '../client/favicon.ico')));


// 穿透cloud.baidu.com/market代理的静态文件，防止404，如cloud.baidu.com/market/version.txt等
app.use(mount(config.appDomain || '/', serve(path.join(__dirname, '/../client/assets'))));
app.use(mount(config.appDomain || '/', serve(path.join(__dirname, '/../dist'))));


app.use(middleware);

if (isDev === 'development') {
    /* eslint-disable */
    const mockMod = require('./www/mock');
    /* eslint-enable */
    const mockRoute = mockMod.default || mockMod;

    app.use(mockRoute.routes());
} else {
    /* eslint-disable */
    const apiMod = require('./www/webapi');
    /* eslint-enable */
    const apiRoute = apiMod.default || apiMod;

    app.use(apiRoute.routes());
}

app.use(serverRender.routes());

app.use(ctx => {
    ctx.status = 404;
    ctx.body = 'Not Found';
});

const PORT = process.env.NODE_PORT || 8103;
app.listen(PORT, () => global.logger.info('Listening on port %s', PORT));
